// pages/test/index.js
const app = getApp();
const service = require("../../service/port.js");
const serviceCard = require("../../service/mycard.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: false,
    hasUserInfo: false,
    mobile: '',
    canIUse: wx.canIUse("button.open-type.getUserInfo"),
    isbindphone: true,
    pageNum: 1, // 当前请求的page
    pageSize: 10, // 请求数据的size
    noData: false,
    productList: [],
    showObj: {
      agent: true,
      diamond: true,
      bankCard: true,
      poster: true,
      balance: true,
      address: true,
      businessCard: true,
      authentication: true,
      qrcode: true,
      comment: true,
      coupon: true,
      member: true,
      cards: true,
      recommend: true,
      allOrder: true
    },
  },
  getList(callback) {
    service.getbannerList({
      "banner": {

        "type": 4, //广告类型（位置） 1：首页banneer广告位 2：首页推广位 3：订单支付完成后页面广告位 4：我的页面底部广告位 5：开屏弹窗广告位 6: 秒杀广告 7：拼团广告 8：打包一口价广告 9：优惠券广告 
      },
      "queryRequest": {
        "pageSize": this.data.pageSize,
        "pageNum": this.data.pageNum
      }
    }, res => {
      console.log(res)
      callback(res)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    service.getshowModel("我的", res => {
      console.log(res)
      var obj = this.data.showObj
      for (let i = 0; i < res.data.length; i++) {
        const element = res.data[i];
        if (element.ufName == "申请代理") {
          obj.agent = element.ufIsOpen == 1 ? true : false
        } else if (element.ufName == "我的钻石") {
          obj.diamond = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "银行卡管理") {
          obj.bankCard = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的海报") {
          obj.poster = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的余额") {
          obj.balance = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的地址") {
          obj.address = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的名片") {
          obj.businessCard = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的认证") {
          obj.authentication = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的二维码") {
          obj.qrcode = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的评论") {
          obj.comment = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "优惠卷") {
          obj.coupon = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的会员") {
          obj.member = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "我的储值卡") {
          obj.cards = element.ufIsOpen == 1 ? true : false
        }else if (element.ufName == "为您推荐") {
          if(element.ufIsOpen==1){
            obj.recommend=true
            wx.showLoading({
              title: "加载中...",
            });
            this.getList(res => {
              wx.hideLoading()
              if (res.code == "00000") {
                if (res.data.rows.length == 0) {
                  this.setData({
                    productList: res.data.rows,
                    noData: true,
                  })
                } else {
                  this.setData({
                    productList: res.data.rows,
                    noData: false,
                  })
                }
              }
        
            })
          }else{
            obj.recommend=false
          }
          
        }else if (element.ufName == "全部订单") {
          obj.allOrder = element.ufIsOpen == 1 ? true : false
        }
      }

    })
    
  },
  getUserInfo: function (e) {
    console.log(e);

    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail;
      const self = this;
      wx.checkSession({
        success: function (res) {
          console.log("处于登录态");
          service.login({
              code: wx.getStorageSync('code').code,
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              id: wx.getStorageSync('qrcodeId') || 0
            },
            (result) => {
              console.log(result);

              wx.setStorageSync("userInfo", result.data);
              self.getphone()
            }
          );
        },
        fail: function (res) {
          wx.login({
            success: (res1) => {
              // console.log(res1)
              wx.setStorageSync("code", res1);
              service.login({
                  code: res1.code,
                  encryptedData: e.detail.encryptedData,
                  iv: e.detail.iv,
                  id: wx.getStorageSync('qrcodeId') || 0
                },
                (result) => {
                  console.log(result);
                  wx.setStorageSync("userInfo", result.data);
                  self.getphone()
                }
              );

              //发送 res.code 到后台换取 openId, sessionKey, unionId
            },
          });
        }
      })

      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true,
      });
    } else {
      wx.showToast({
        title: '授权失败！',
        icon: 'none',
        duration: 2000
      })
    }
  },
  goOrdera(e) {
    //console.log(e);
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/mine/order/unpayList/index",
      });
    }
  },
  goOrderb(e) {
    //console.log(e);
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/mine/order/unreviceList/index",
      });
    }
  },
  goOrderc(e) {
    //console.log(e);
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/mine/order/completeList/index",
      });
    }
  },
  goOrderd(e) {
    //console.log(e);
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/mine/order/refundList/index",
      });
    }
  },
  goToProductDetail(e) {
    // console.log(item.currentTarget.dataset.id);
    wx.navigateTo({
      url: "/pages/product/productDetail/index?id=" +
        e.currentTarget.dataset.id,
    });
  },

  closeTo() {
    wx.showToast({
      title: '暂未开放',
      icon: 'none',
      duration: 2000
    })
  },
  showPopup: function () {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
      return
    }
    wx.navigateTo({
      url: "/pages/mine/qrcode/index",
    });
  },
  toPoster() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
      return
    }
    wx.navigateTo({
      url: "/pages/mine/posterList/index",
    });
  },
  getPhoneNumber(e) {
    console.log(e);
    console.log(e.detail.iv);
    console.log(e.detail.encryptedData);
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
      return
    }
    if (!e.detail.encryptedData) {
      return
    }
    // wx.checkSession({
    //   success: function (res) {
    //     console.log("处于登录态");
    //     console.log(wx.getStorageSync('code').code)

    //     service.getPhone({
    //       'code': wx.getStorageSync('code').code,
    //       "phone": e.detail.encryptedData,
    //       "iv": e.detail.iv
    //     }, res => {

    //       if (res.status == 200) {
    //         Toast.success('绑定成功!')
    //       } else {
    //         Toast.fail(res.error)
    //       }

    //     })
    //   },
    //   fail: function (res) {
    wx.login({
      success: (res1) => {
        // console.log(res1)
        wx.setStorageSync("code", res1);
        service.getPhone({
          'code': res1.code,
          "phone": e.detail.encryptedData,
          "iv": e.detail.iv,
          'customerId': wx.getStorageSync("userInfo").id
        }, res => {

          if (res.code == 500) {
            Toast.fail(res.error)
            return
          }
          Toast.success('绑定成功!')
          this.setData({
            isbindphone: false,
            mobile: res.data
          })

        })

        //发送 res.code 到后台换取 openId, sessionKey, unionId
      },
    });
    //   }
    // })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo.userInfo,
        hasUserInfo: true,
      });
      this.getphone()

    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = (res) => {
        //console.log(res);
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true,
        });
        this.getphone()
      };
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: (res) => {
          app.globalData.userInfo = res.userInfo;

          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true,
          });
          this.getphone()
        },
      });
    }

  },
  getphone: function () {
    if (!wx.getStorageSync('userInfo').id) {
      Toast.fail('请先登录！')
    } else {
      console.log(wx.getStorageSync('userInfo'))
      if (wx.getStorageSync('userInfo').mobile != null && wx.getStorageSync('userInfo').mobile != "") {
        this.setData({
          mobile: wx.getStorageSync('userInfo').mobile,
          isbindphone: false
        })
      } else {

        this.setData({
          isbindphone: true
        })
        let userId = wx.getStorageSync('userInfo').id

        wx.navigateTo({
          url: '/pages/phone/index?userId=' + userId,
        })
      }

    }

  },
  goaddress() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/mine/address/index",
      });
    }
  },
  couponTo() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/coupon/index",
      });
    }
  },
  goComment() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/mine/comment/index",
      });
    }
  },
  cardsTo(){
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/deposit/index/index",
      });
    }
  },
  memberTo(){
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: "/pages/deposit/vip/index",
      });
    }
  },
  mycard() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.showLoading({
        title: "加载中...",
      });
      serviceCard.getDefaultCard(wx.getStorageSync('userInfo').id, res => {
        //console.log(res)
        wx.hideLoading();
        if (res.data == null) {
          wx.navigateTo({
            url: '/pages/mycard/edit/index',
          })
        } else {
          wx.navigateTo({
            url: "/pages/mycard/index",
          });
        }
      })

    }
  },
  /**
   * 认证
   */
  myauthentication() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: '/pages/authentication/index',
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  toDelegete() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
      return
    }
    wx.navigateTo({
      url: '/pages/agency/index',
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      pageNum: 1,
      noData: false,
    });
    this.getList((res) => {
      console.log(res);
      if (res.code == "00000") {
        if (res.data.rows.length == 0) {
          this.setData({
            productList: res.data.rows,
            noData: true,

          })
        } else {
          this.setData({
            productList: res.data.rows,
            noData: false,
          })
        }

      }
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.noData) return;
    wx.stopPullDownRefresh();
    const prolist = this.data.productList;
    let page = this.data.pageNum;
    this.setData({
      // 每次下拉 page+1
      pageNum: ++page,
    });
    this.getList((res) => {
      if (res.data.rows.length == 0) {
        this.setData({
          noData: true,

        });
      } else {
        res.data.rows.forEach((item) => {

          prolist.push(item);
        });
        this.setData({
          productList: prolist,
        });
      }
      // 隐藏加载状态
      // wx.hideNavigationBarLoading()
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  toBackCard(e) {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: '/pages/mine/bankcard/index',
      })

    }
  },
  toMineYuE() {
    if (app.globalData.userInfo == null) {
      Toast.fail('请先登录！')
    } else {
      wx.navigateTo({
        url: '/pages/mine/balance/index',
      })

    }
  }
})